package reflection.p2;

import com.sun.net.httpserver.Filter;
import reflection.p1.Person;
import java.lang.reflect.*;
public class Example01 {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
     Class<?>c1= Person.class;
     //获取当前类及其父类的public字段
        Field []fields=c1.getFields();
//获取当前类的所有字段
Field[]fields1=c1.getDeclaredFields();
        System.out.println("获取当前类及其父类的public字段");
        for (int i = 0; i <fields.length ; i++) {
            int modifiers = fields[i].getModifiers();
            System.out.println(Modifier.toString(modifiers)+" "+fields[i].getType().getSimpleName()+" "+fields[i].getName()+" ");
        }
        System.out.println("获取当前类的所有字段");
        for (int i = 0; i <fields1.length ; i++) {
            int modifiers = fields1[i].getModifiers();
            System.out.println(Modifier.toString(modifiers)+" "+fields1[i].getType().getSimpleName()+" "+fields1[i].getName()+" ");
        }

        //获取构造方法并实例化对象
        //全参的构造函数
        Constructor<?>constructor=c1.getConstructor(String.class,Integer.class);
Person p1= (Person) constructor.newInstance("张三",45);
        System.out.println("name:"+p1.getName()+"   age:"+p1.getAge());
//无参的构造函数
        Constructor<?>constructor1=c1.getConstructor();
        Person p2= (Person) constructor1.newInstance();
        System.out.println("name:"+p2.getName()+"   age:"+p2.getAge());

        //获取无参的方法
        Method method=c1.getMethod("sayHello");
        method.invoke(p1);
//获取有参的方法
        Method method1=c1.getMethod("say", String.class);
        method1.invoke(p1,"张三");
//获取私有的方法
        Method method2=c1.getDeclaredMethod("sayPrivate");
        //突破权限
        method2.setAccessible(true);
        method2.invoke(p1);
//调用静态方法
        Method method3=c1.getMethod("sayStatic");
        method3.invoke(null);
    }
}
